package com.ysu.his.admin.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler
{

    // 存储用户ID -> Session 的映射
    private static final ConcurrentHashMap<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    // 用户连接时触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = getUserId(session); // 从参数或认证信息中获取用户ID
        userSessions.put(userId, session);
        System.out.println(userId + " 已连接");
    }

    // 接收到客户端消息时触发
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());
    }

    // 用户断开连接时触发
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = getUserId(session);
        userSessions.remove(userId);
        System.out.println(userId + " 已断开");
    }

    // 向指定用户发送消息
    public void sendMessageToUser(String userId, String message) throws IOException
    {
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        }
    }

    // 获取用户ID方法（可根据业务调整）
    private String getUserId(WebSocketSession session) {
        // 示例：从URL参数获取 ws://localhost:8080/ws?userId=123
        String uri = session.getUri().toString();
        return uri.substring(uri.indexOf("=") + 1);
    }
}

